import { SET_TOKEN, SET_NAME, SET_SEMESTER } from './mutations-type'
import { getToken, setToken, removeToken } from '../utils/auth'
import { login, logout, getInfo } from '../api/users'
import { getSemesterInfo } from "../api/dictionaries";

export default {
    login({ commit }, { account, password }) {
        return new Promise((resolve, reject) => {
            login({ password, account: account.trim() })
                .then(response => {
                    if (response.data.code == 500) {
                        reject()
                    }
                    const { data } = response
                    commit(SET_TOKEN, data.token)
                    setToken(data.token)
                    resolve()
                })
                .catch(error => {
                    console.log(error)
                    reject(error)
                })
        })
    },
    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo()
                .then(response => {
                    // console.log(response)
                    const { data } = response
                    const { result } = data
                    commit(SET_NAME, result)
                    resolve(data)
                })
                .catch(error => {
                    reject(error)
                })
        })
    },
    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout()
                .then(response => {
                    commit(SET_TOKEN, '')
                    commit(SET_NAME, '')
                    removeToken()

                    resolve()
                })
                .catch(error => {
                    console.log(error)
                    reject(error)
                })
        })
    },
    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit(SET_TOKEN, '')
            removeToken()
            resolve()
        })
    },
    // get new semester
    async getNewSemester({ commit, state }) {
        let { data: res } = await getSemesterInfo();
        let nowSemester = res.result[0].name
        commit(SET_SEMESTER, nowSemester)

    },
}